package com.huanzhidadi.single.delayquit;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DelayQuitClient {
    // 有效期
    public static final long delayTime = 3000;

    public static DelayQueue<QuitUserKey> delayQueue = new DelayQueue<>();

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(1, new DaemonThreadFactory());
        UserQuitConsumer consumer = new UserQuitConsumer(delayQueue);
        executor.submit(consumer);

        userLogin("user1");

        userLogin("user2");

        userOper("user1");

        userOper("user1");

        userOper("user1");

        try {
            executor.awaitTermination(3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executor.shutdown();
    }

    private static void userLogin(String userKey) {
        try {
            QuitUserKey quitUserKey = new QuitUserKey(userKey, delayTime);
            delayQueue.put(quitUserKey);
            log.info(userKey + "登陆成功");
            delayQueue.forEach(item -> System.out.println("当前存活：" + item.getKey()));
            Thread.sleep(600l);
        } catch (Exception e) {
            log.error("模拟登陆发生异常。", e);
        }
    }

    private static void userOper(String userKey) {
        try {
            QuitUserKey quitUserKey = new QuitUserKey(userKey, delayTime);
            delayQueue.remove(quitUserKey);
            delayQueue.put(quitUserKey);
            log.info(userKey + "操作成功");
            delayQueue.forEach(item -> System.out.println("当前存活：" + item.getKey()));
            Thread.sleep(2000l);
        } catch (Exception e) {
            log.error("模拟操作发生异常。", e);
        }
    }

}
